package com.iwhalecloud.bss.kite.cucc.service.attr.linkhandler;

import com.iwhalecloud.bss.kite.client.enums.TriggerStrategy;
import com.iwhalecloud.bss.kite.common.constant.ErrorConsts;
import com.iwhalecloud.bss.kite.common.constant.KeyConsts;
import com.iwhalecloud.bss.kite.common.constant.ServiceOfferConsts;
import com.iwhalecloud.bss.kite.common.util.KiteListUtils;
import com.iwhalecloud.bss.kite.common.util.KiteMapUtils;
import com.iwhalecloud.bss.kite.common.util.KiteStringUtils;
import com.iwhalecloud.bss.kite.cucc.client.api.inf.IInfServiceBus;
import com.iwhalecloud.bss.kite.cucc.common.constant.LocalCallClientEnum;
import com.iwhalecloud.bss.kite.cucc.common.constant.LocalKeyConsts;
import com.iwhalecloud.bss.kite.cucc.service.attr.handler.DeliveryInformationAttrHandler;
import com.iwhalecloud.bss.kite.cucc.service.inf.InfServiceBus;
import com.iwhalecloud.bss.kite.dataservice.cache.DcPublicCache;
import com.iwhalecloud.bss.kite.dataservice.entity.DcPublic;
import com.iwhalecloud.bss.kite.listener.handler.attr.annotation.AttrHandler;
import com.iwhalecloud.bss.kite.listener.handler.attr.impl.AbstractAttrLinkageHandler;
import com.iwhalecloud.bss.kite.manager.api.IQuerySceneInstService;
import com.iwhalecloud.bss.kite.manager.inst.KiteAttr;
import com.iwhalecloud.bss.kite.manager.inst.KiteAttrValue;
import com.iwhalecloud.bss.kite.manager.inst.KiteInst;
import com.iwhalecloud.bss.kite.service.attr.AttrData;
import com.ztesoft.bss.common.exception.BssException;
import com.ztesoft.bss.common.util.ContextUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

/**
 * Description:送达信息处理类
 * File Name:DeliveryInformationAttrLinkHandler
 * Modification History:
 * Date             Author      Version     Description
 * ------------------------------------------------------------------
 * 2021-4-8 9:44   邱萌         1.0       1.0 Version
 **/
@Service
@AttrHandler(DeliveryInformationAttrHandler.class)
public class DeliveryInformationAttrLinkHandler  extends AbstractAttrLinkageHandler<AttrData> {
    @Autowired
    private InfServiceBus infServiceBus;

    @Autowired
    private IQuerySceneInstService querySceneInstService;

    @Override
    public void handle(KiteAttr kiteAttr, KiteInst kiteInst, AttrData attrData) {
        String oppo_init = querySceneInstService.getExtParameterValue(attrData.getSceneInstId(), "oppo_init");
        if((KiteStringUtils.isEmpty(kiteAttr.getPreValue()) && KiteStringUtils.equals(kiteAttr.getDefaultValue(),kiteAttr.getValue()))){
            return;
        }
        //根据运营方下来选项值调用接口获取运营专员数据
        if ("200001046".equals(kiteAttr.getFieldName()) && KiteStringUtils.isNotEmpty(kiteAttr.getValue())) {
            //DcPublic cfg = DcPublicCache.get("20210427173933", kiteAttr.getValue());
            KiteAttr attachment = kiteInst.getAttr("200004289");
            Map map=new HashMap();
            map.put("carrierId",kiteAttr.getValue());
            List<String> list = infServiceBus.queryOpeList(map);
            if(KiteListUtils.isEmpty(list) && !KiteStringUtils.equals(oppo_init,"T")){
                BssException.throwOut("", "","未查到运营专员账号信息，请与大数据公司数达信息产品平台联系！");
            }
            List<KiteAttrValue> attrValues = new ArrayList<>();
            list.stream().forEach(name -> {
                KiteAttrValue attrValue = new KiteAttrValue();
                attrValue.setAttrValue(name);
                attrValue.setAttrValueName(name);
                attrValues.add(attrValue);
            });
            if (Objects.nonNull(attachment)) {
                attachment.setValue("");
                attachment.setAttrValues(attrValues);
            }
        }

        //根据运营专员下拉选项设置运营专员的值
        if ("200004289".equals(kiteAttr.getFieldName()) && KiteStringUtils.isNotEmpty(kiteAttr.getValue())) {
            KiteAttr attachment = kiteInst.getAttr("200001191");
            if (Objects.nonNull(attachment)) {
                attachment.setValue(kiteAttr.getValue());
            }
        }
        //根据合作伙伴名称设置合作伙伴ID的值
        if ("200001193".equals(kiteAttr.getFieldName()) && KiteStringUtils.isNotEmpty(kiteAttr.getValue())) {
            KiteAttr attachment = kiteInst.getAttr("200001192");
            if (Objects.nonNull(attachment)) {
                attachment.setValue(kiteAttr.getValue());
            }
        }

        String group_user_name="";
        String opp_user_name="";
        List<KiteAttr> groupUserkiteAttrs = querySceneInstService
            .listCommonAttrsByModuleId(attrData.getSceneInstId(), LocalKeyConsts.GROUPUSERINFO_MODULEID).stream().filter(
                //.listCommonAttrsByModuleId(KiteWebContext.getContextNew().getCurrentSceneInstId(), LocalKeyConsts.GROUPUSERINFO_MODULEID).stream().filter(
                attr -> !KiteStringUtils.isEqual("H", attr.getShowType()) && !KiteStringUtils
                    .isEqual("1", attr.getObjId())).collect(Collectors.toList());
        for (KiteAttr attr : groupUserkiteAttrs) {
            if (KiteStringUtils.equals("group_user_name", attr.getFieldName())) {
                group_user_name = attr.getValue() == null ? "" : attr.getValueDesc();
            }else  if(KiteStringUtils.equals("USR0001", attr.getFieldName())){
                opp_user_name=attr.getValue() == null ? "" : attr.getValueDesc();
            }
        }
        // 合作伙伴类型
        KiteAttr attr1 = kiteInst.getAttr("200004284");
        //合作伙伴名称
        KiteAttr attr2 = kiteInst.getAttr("200001193");
        //运营方
        KiteAttr attr4 = kiteInst.getAttr("200001046");
        //业务行业类型
        KiteAttr attr5 = kiteInst.getAttr("200001047");
        //重提初始化不校验
        Map<String, Object> extParams = ContextUtil.getLoginInfo().getUserInfo().getExtParams();
        if (KiteMapUtils.isNotEmpty(extParams) && extParams.containsKey("nodeCode")) {
            return;
        }
        // 变更业务的场景初始化过程中不校验
        if (!"1068".equals(attrData.getServiceOfferId())
            && !KeyConsts.IFTRUE_T.equals(querySceneInstService.getExtParameterValue(attrData.getSceneInstId(), LocalKeyConsts.BUSI_CHANGE_SCENE))
            && !"workOrder".equals(querySceneInstService.getExtParameterValue(attrData.getSceneInstId(), "initSource"))) {
            return;
        }
        if(KiteStringUtils.equals(attr4.getValue(), attr4.getOriginValue())&&KiteStringUtils.equals(attrData.getServiceOfferId(), "2826")&&KiteStringUtils.equals("100006370", attr1.getValue())){
            return;
        }
        if(KiteStringUtils.equals("100006370", attr1.getValue())) {//新增
            attr2.setAttrValueTypeId("98C");
            Map map = new HashMap();
            if (KiteStringUtils.isNotEmpty(group_user_name)) {
                map.put("ENT_NAME", attr4.getValueDesc() + "-" + group_user_name + "-" + attr5.getValueDesc());
                Map<String, Object> detailMap = infServiceBus.queryNewPartnerQuery(map);
                String RESULT_CODE = (String) detailMap.get("RESULT_CODE");
                if (RESULT_CODE.equals("0005")) {
                    ErrorConsts.INF_INVOKE_ERROR.throwOut(LocalCallClientEnum.INF_COMMON_URL.getServiceCode(), "合作伙伴已存在并无法保存，请修改", "");
                } else {
                    attr2.setValue(attr4.getValueDesc() + "-" + group_user_name + "-" + attr5.getValueDesc());
                    attr2.setValueDesc(attr4.getValueDesc() + "-" + group_user_name + "-" + attr5.getValueDesc());
                }
            }
        }else  if(KiteStringUtils.equals("100007576", attr1.getValue())) {//复用
            String oppoNum=this.querySceneInstService.getExtParameterValue(attrData.getSceneInstId(), "oppoNum");
            if(KiteStringUtils.isEmpty(oppoNum)){
                oppoNum=opp_user_name;
            }
            Map map=new HashMap();
            map.put("BUSINESS_NO",oppoNum);
            Map<String, Object> datamap = infServiceBus.partnerReuseQuery(map);
            List<String> list = (List) datamap.get("RESULT_DATA");
            List<KiteAttrValue> attrValues = new ArrayList<>();
            list.stream().forEach(name -> {
                KiteAttrValue attrValue = new KiteAttrValue();
                attrValue.setAttrValue(name);
                attrValue.setAttrValueName(name);
                attrValues.add(attrValue);
            });
            attr2.setAttrValueTypeId("98A");
            attr2.setAttrValues(attrValues);
        }
    }

    @Override
    public void handleStyle(KiteAttr kiteAttr, KiteInst kiteInst, AttrData attrData) {

    }
}
